package com.dmall.opening.up.records.util;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class Https {

    @Bean("spring.rest.template.http.client")
    public RestTemplate restTemplate(@Value("${spring.rest.template.connect.timeout:1000}") Integer connectTimeout,
                                     @Value("${spring.rest.template.read.timeout:2000}") Integer readTimeout) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(20);
        connectionManager.setDefaultMaxPerRoute(10);

        RequestConfig config = RequestConfig
                .custom()
                .setConnectionRequestTimeout(connectTimeout)
                .setSocketTimeout(readTimeout)
                .setConnectTimeout(connectTimeout)
                .build();

        HttpClient client = HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(config).build();

        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
        return new RestTemplate(requestFactory);
    }
}
